<template>
  <div class="image-render" :style="wrapperStyle">
    <div v-if="value.captionBefore || value.fieldName" class="caption before">
      <span v-if="value.prefixSymbol" class="prefix">{{ mapPrefix(value.prefixSymbol) }}</span>
      <strong v-if="value.fieldName">{{ value.fieldName }}</strong>
      <span v-if="value.captionBefore">{{ value.captionBefore }}</span>
    </div>

    <div v-if="imgUrl" class="img-box">
      <img :src="imgUrl" :alt="value.image?.alt || ''" :style="imgStyle" />
    </div>

    <div v-if="value.captionAfter" class="caption after">
      <span>{{ value.captionAfter }}</span>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  modelValue: { type: Object, default: () => ({}) }
})

const value = computed(() => props.modelValue || {})
const imgUrl = computed(() => value.value?.image?.previewUrl || value.value?.image?.url || '')

const cmToPx = (cm) => {
  const dpi = 96
  const inch = (cm || 0) / 2.54
  return `${inch * dpi}px`
}

const wrapperStyle = computed(() => ({
  textAlign: (value.value?.alignment || value.value?.labelAlign || 'left').includes('indent-')
    ? 'left'
    : (value.value?.labelAlign || 'left'),
  margin: '8px 0'
}))

const imgStyle = computed(() => {
  const w = value.value?.image?.widthCm
  const h = value.value?.image?.heightCm
  const style = {}
  if (w) style.width = cmToPx(w)
  if (h) style.height = cmToPx(h)
  style.objectFit = value.value?.image?.objectFit || 'contain'
  return style
})

const mapPrefix = (p) => {
  const m = {
    dot_circle: '⏺',
    star: '✧',
    pointer: '☞',
    arrow_curved: '⮚',
    square: '⯀'
  }
  return m[p] || ''
}
</script>

<style scoped>
.image-render { width: 100%; }
.img-box { display: inline-block; }
.caption { margin: 4px 0; }
.prefix { margin-right: 4px; }
</style>


